package 数组;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @Author Weton Li
 * @Date 2021/4/22 17:16
 */
public class 多数元素 {
    public static void main(String[] args) {
        int[] input1 = {3,2,3};
        int[] input2 = {2,2,1,1,1,2,2};
        System.out.println(majorityElement(input1));
        System.out.println(method(input2));
    }

    public static int method(int[] arr){
        int n = arr.length;
        int targetCount = n/2;
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int num : arr) {
            Integer count = map.getOrDefault(num, 0);
            map.put(num,++count);
        }

        // 可以
//        Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet().iterator(); // 遍历集合
//        while (iterator.hasNext()) {
//            Map.Entry<Integer, Integer> next = iterator.next();
//            Integer c = next.getValue();
//            if (c > targetCount) {
//                return next.getKey();
//            }
//        }
        // 也可
        Set<Map.Entry<Integer, Integer>> countEntrySet = map.entrySet();
        for (Map.Entry<Integer, Integer> entry : countEntrySet) {
            if (entry.getValue()>targetCount) {
                return entry.getValue();
            }
        }

        return -1;
    }


    public static int majorityElement(int[] nums) {
        HashMap<Integer, Integer> mapCount = new HashMap<>();
        for (int num : nums) {
            Integer count = mapCount.getOrDefault(num, 0);
            mapCount.put(num, ++count);
        }
        Map.Entry<Integer,Integer> tempMap = null;

        for (Map.Entry<Integer, Integer> mapCountEntry : mapCount.entrySet()) {
            if (tempMap == null || mapCountEntry.getValue() > tempMap.getValue()) {
                tempMap = mapCountEntry;
            }
        }
        return tempMap.getKey();
    }
}
